#!/usr/bin/env ruby

require 'git'
require 'gitlab'

CLONE_DIR = ARGV.first
if CLONE_DIR.nil?
  puts "usage:\n  CI_API_V4_URL=https://<gitlab>/api/v4 GITLAB_API_PRIVATE_TOKEN=<TOKEN> gitlab-clone <clone dir>"
  puts "options:\n  IGNORE_ARCHIVED_PROJECT # ignore archived project"
  exit
end

IGNORE_ARCHIVED_PROJECT = ENV['IGNORE_ARCHIVED_PROJECT']
USE_HTTP_REPO = ENV['USE_HTTP_REPO']
FileUtils.mkdir_p(CLONE_DIR)
Gitlab.projects.auto_paginate.map do |repo|
  next if !IGNORE_ARCHIVED_PROJECT.nil? && repo.archived

  save_dir = repo['path_with_namespace']
  puts save_dir
  path = File.join(CLONE_DIR, save_dir)
  repo_url = repo[ USE_HTTP_REPO.nil? ? 'ssh_url_to_repo' : 'http_url_to_repo' ]
  if !File.directory?(path)
    puts 'clone'
    Git.clone(repo_url, save_dir, path: CLONE_DIR)
    puts 'clone end'
  else
    puts 'fetch'
    g = Git.open(path)
    r = g.remote()
    g.set_remote_url(r.name, repo_url)
    g.fetch(prune: true, 'prune-tags': true, force: true)
    puts 'fetch end'
  end
rescue => e
  puts "error: #{e}"
ensure
  puts
end
